package com.hxkj.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hxkj.client.service.LabelConfServiceClient;
import com.hxkj.domain.po.AuthUser;
import com.hxkj.domain.po.LabelExt;
import com.hxkj.domain.po.LabelManagement;
import com.hxkj.domain.po.LabelUsageInfo;
import com.hxkj.domain.vo.LabelManagementVO;
import com.hxkj.service.LabelConfService;
import com.hxkj.token.utils.TokenUtils;
import com.platform.common.domain.exception.CustomMessageException;
import com.platform.common.domain.result.ParameterDataStruct;
import com.platform.common.domain.result.ResultDataStruct;
import com.platform.common.domain.result.ResultMessageStruct;
import com.platform.common.domain.result.ResultPageStruct;
import com.platform.common.domain.to.PageTo;
import com.platform.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class LabelConfServiceImpl implements LabelConfService{


    @Autowired
    private LabelConfServiceClient labelConfServiceClient;

    @Autowired
    private TokenUtils tokenUtils;

    @Override
    public void save(JSONObject jsonObject) throws Exception {
        if(jsonObject == null){
            throw new CustomMessageException("请填写有效的数据！");
        }
        LabelManagement labelManagement = JSONObject.toJavaObject(jsonObject, LabelManagement.class);
        if(labelManagement == null){
            throw new CustomMessageException("不能保存空标签数据！");
        }
        if(StringUtils.isBlank(labelManagement.getName())||
                StringUtils.isBlank(labelManagement.getLabelName())){
            throw new CustomMessageException("名称/标签名为空，请填写！");
        }

        AuthUser auser = (AuthUser) tokenUtils.getTokenUserInfo();
        labelManagement.setCreateor(auser.getUserId());
        labelManagement.setCreateTime(System.currentTimeMillis());
        labelManagement.setUpdateTime(System.currentTimeMillis());
        labelManagement.setModifyBy(auser.getUserId());
        labelManagement.setDelTag(0);


        Map<String, Object> map = new HashMap<>();
        map.put("data",labelManagement);
        map.put("extList",labelManagement.getExtlist());
        //map.put("usageList",usages);

        ResultMessageStruct result = labelConfServiceClient.save(map);
        if(result.getCode() != 200){
            throw new CustomMessageException("保存标签失败");
        }
    }

    @Override
    public void saveLabel(LabelManagement labelManagement) throws Exception {
        if(StringUtils.isBlank(labelManagement.getName())||
                StringUtils.isBlank(labelManagement.getLabelName())){
            throw new CustomMessageException("名称/标签名为空，请填写！");
        }
        AuthUser auser = (AuthUser) tokenUtils.getTokenUserInfo();
        labelManagement.setCreateor(auser.getUserId());
        labelManagement.setCreateTime(System.currentTimeMillis());
        labelManagement.setUpdateTime(System.currentTimeMillis());
        labelManagement.setModifyBy(auser.getUserId());
        labelManagement.setDelTag(0);
        ResultMessageStruct result = labelConfServiceClient.saveLabel(labelManagement);
        if(result.getCode() != 200){
            throw new CustomMessageException("保存标签失败");
        }
    }

    @Override
    public LabelManagement get(LabelManagement labelManagement) throws Exception {
        if(labelManagement.getLabelId() == null){
            throw new RuntimeException("标签ID不能为空!");
        }
        ResultDataStruct<LabelManagement> result = labelConfServiceClient.getLabelInfo(labelManagement);
        if(result.getCode() != 200){
            throw new CustomMessageException("没有符合条件的数据");
        }
        return result.getData();
    }

    @Override
    public ResultPageStruct<LabelManagementVO> getLabelList(LabelManagement labelManagement, PageTo pageParam) throws Exception {
        if (pageParam.getPageNum() == null || pageParam.getPageSize() == null) {
            pageParam.setPageNum(1);
            pageParam.setPageSize(10);
        }
        ResultPageStruct<LabelManagementVO> result = new ResultPageStruct<>();
        ParameterDataStruct<LabelManagement> parameterDataStruct = new ParameterDataStruct<>();
        parameterDataStruct.setData(labelManagement);
        parameterDataStruct.setPageTo(pageParam);
        try{
            result = labelConfServiceClient.getLabelList(parameterDataStruct);
        }catch (Exception e){
            e.printStackTrace();
            log.error("获取标签列表失败:{}", e.getMessage());
        }
        return result;
    }

    @Override
    public void modify(JSONObject jsonObject) throws Exception {
        if(jsonObject == null){
            throw new CustomMessageException("请填写有效的数据！");
        }
        LabelManagement labelManagement = JSONObject.toJavaObject(jsonObject, LabelManagement.class);
        if(labelManagement == null){
            throw new CustomMessageException("不能修改空标签数据！");
        }
        if(labelManagement.getLabelId() == null){
            throw new CustomMessageException("标签ID不能为空!");
        }

        AuthUser auser = (AuthUser) tokenUtils.getTokenUserInfo();
        labelManagement.setCreateor(auser.getUserId());
        labelManagement.setCreateTime(System.currentTimeMillis());
        labelManagement.setDelTag(0);


        Map<String, Object> map = new HashMap<>();
        map.put("data",labelManagement);
        map.put("extList",labelManagement.getExtlist());

        ResultMessageStruct result = labelConfServiceClient.modifyLabel(map);
        if(result.getCode() != 200){
            throw new CustomMessageException("修改标签失败");
        }
    }

    @Override
    public void remove(String labelIds) throws Exception {
        if(StringUtils.isBlank(labelIds)){
            throw new CustomMessageException("标签ID不能为空!");
        }
        AuthUser auser = (AuthUser) tokenUtils.getTokenUserInfo();

        ResultMessageStruct result = labelConfServiceClient.deleteLabel(labelIds);
        if(result.getCode() != 200){
            throw new CustomMessageException("删除标签失败");
        }
    }


    /**
     * 扩展表和用法表的新增修改
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @Override
    public ResultMessageStruct editLabelPlus(JSONObject jsonObject) throws Exception{
        ResultMessageStruct result = new ResultMessageStruct();

        AuthUser auser = (AuthUser) tokenUtils.getTokenUserInfo();
        //JSONObject jsonObject = JSONObject.parseObject(str);
        String type = jsonObject.getString("type");
        String operate = jsonObject.getString("operate");
        if(StringUtils.isBlank(type)||StringUtils.isBlank(operate)){
            result.setMessage("数据类型和操作类型不能为空!");
            result.setCode(335);
            return result;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("type",type);
        map.put("operate",operate);
        JSONArray json = jsonObject.getJSONArray("data");
        List list = new ArrayList();
        if(json != null && json.size()>0) {
            if ("ext".equals(type)) {
                for (Object o : json) {
                    JSONObject obj = (JSONObject) o;
                    LabelExt labelExt = JSONObject.toJavaObject(obj, LabelExt.class);
                    if ("save".equals(operate)) {
                        labelExt.setCreateor(auser.getUserId());
                        labelExt.setCreateTime(System.currentTimeMillis());
                        list.add(labelExt);
                    } else {
                        labelExt.setModifyBy(auser.getUserId());
                        labelExt.setUpdateTime(System.currentTimeMillis());
                        list.add(labelExt);
                    }
                }
            } else {
                for (Object o : json) {
                    JSONObject obj = (JSONObject) o;
                    LabelUsageInfo labelUsageInfo = JSONObject.toJavaObject(obj, LabelUsageInfo.class);
                    if ("save".equals(operate)) {
                        labelUsageInfo.setCreateor(auser.getUserId());
                        labelUsageInfo.setCreateTime(System.currentTimeMillis());
                        list.add(labelUsageInfo);
                    } else {
                        labelUsageInfo.setUpdateTime(System.currentTimeMillis());
                        labelUsageInfo.setModifyBy(auser.getUserId());
                        list.add(labelUsageInfo);
                    }
                }
            }
        }else{
            result.setMessage("修改/删除数据集合为空!");
            result.setCode(336);
            return result;
        }
        map.put("data",list);
        result = labelConfServiceClient.editLabelPlus(map);
        return result;
    }

    /**
     * 扩展表和用法表的删除
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @Override
    public ResultMessageStruct deleteLabelPlus(JSONObject jsonObject) throws Exception{
        ResultMessageStruct result = new ResultMessageStruct();
        //JSONObject jsonObject = JSONObject.parseObject(str);
        String type = jsonObject.getString("type");
        if(StringUtils.isBlank(type)){
            result.setMessage("数据类型不能为空!");
            result.setCode(337);
            return result;
        }
        JSONObject json = jsonObject.getJSONObject("data");
        if(StringUtils.isNotBlank(json.getString("labelId"))||
                StringUtils.isNotBlank(json.getString("labelExtId"))||
                StringUtils.isNotBlank(json.getString("labelUsageId"))){
            if("ext".equals(type)){
                LabelExt labelExt = JSONObject.toJavaObject(json, LabelExt.class);
                return labelConfServiceClient.deleteLabelExt(labelExt);
            }else{
                LabelUsageInfo labelUsageInfo = JSONObject.toJavaObject(json, LabelUsageInfo.class);
                return labelConfServiceClient.deleteLabelUsageInfo(labelUsageInfo);
            }
        }else{
            result.setMessage("标签主键不能为空!");
            result.setCode(338);
            return result;
        }

    }

    /************************标签扩展表相关业务****************************/


    @Override
    public ResultMessageStruct saveLabelExt(LabelExt labelExt) throws Exception {
        AuthUser auser = (AuthUser) tokenUtils.getTokenUserInfo();
        labelExt.setCreateor(auser.getUserId());
        labelExt.setCreateTime(System.currentTimeMillis());
        ResultMessageStruct result = labelConfServiceClient.saveLabelExt(labelExt);
        return result;
    }

    @Override
    public ResultDataStruct<List<LabelExt>> getLabelExt(LabelExt labelExt) throws Exception {
        return labelConfServiceClient.getLabelExtList(labelExt);
    }

    @Override
    public ResultMessageStruct modifyLabelExt(LabelExt labelExt) throws Exception {
        AuthUser auser = (AuthUser) tokenUtils.getTokenUserInfo();
        labelExt.setModifyBy(auser.getUserId());
        labelExt.setUpdateTime(System.currentTimeMillis());
        ResultMessageStruct result = labelConfServiceClient.modifyLabelExt(labelExt);
        return result;
    }

    @Override
    public ResultMessageStruct removeLabelExt(LabelExt labelExt) throws Exception {
        return labelConfServiceClient.deleteLabelExt(labelExt);
    }

    /************************标签使用情况表相关业务****************************/

    @Override
    public ResultMessageStruct saveLabelUsage(LabelUsageInfo labelUsageInfo) throws Exception {
        AuthUser auser = (AuthUser) tokenUtils.getTokenUserInfo();
        labelUsageInfo.setCreateor(auser.getUserId());
        labelUsageInfo.setCreateTime(System.currentTimeMillis());
        ResultMessageStruct result = labelConfServiceClient.saveLabelUsageInfo(labelUsageInfo);

        return result;
    }

    @Override
    public ResultDataStruct<List<LabelUsageInfo>> getLabelUsage(LabelUsageInfo labelUsageInfo) throws Exception {
        return labelConfServiceClient.getLabelUsageInfoList(labelUsageInfo);
    }

    @Override
    public ResultMessageStruct modifyLabelUsage(LabelUsageInfo labelUsage) throws Exception {
        AuthUser auser = (AuthUser) tokenUtils.getTokenUserInfo();
        labelUsage.setUpdateTime(System.currentTimeMillis());
        labelUsage.setModifyBy(auser.getUserId());
        ResultMessageStruct result = labelConfServiceClient.modifyLabelUsageInfo(labelUsage);
        return result;
    }

    @Override
    public ResultMessageStruct removeLabelUsage(LabelUsageInfo labelUsage) throws Exception {
        return labelConfServiceClient.deleteLabelUsageInfo(labelUsage);
    }

    public static void main(String[] args) {

        JSONObject json = new JSONObject();
        json.put("labelId",1);
        json.put("comment","test");
        json.put("delTag",0);
        json.put("labelName","test");
        json.put("name","test");
        json.put("sources","test");

        JSONArray array1 = new JSONArray();
        JSONObject jsonext = new JSONObject();
        jsonext.put("allowValue","ceshi");
        jsonext.put("dataType",1);
        jsonext.put("labelExtId",1);
        jsonext.put("labelId",1);
        jsonext.put("name","testExt");
        array1.add(jsonext);

        JSONArray array2 = new JSONArray();
        JSONObject jsonusage = new JSONObject();
        jsonusage.put("number",43);
        jsonusage.put("publishingPlatform",1);
        jsonusage.put("labelUsageId",1);
        jsonusage.put("labelId",1);
        jsonusage.put("templetName","testUsage");
        array2.add(jsonusage);

//        json.put("extList",array1);
//        json.put("usageList",array2);

        JSONObject main = new JSONObject();
        main.put("data",json);
        main.put("extList",array1);
        main.put("usageList",array2);

//        System.out.println(main);
//        System.out.println(main.toJSONString());

        String str = main.toJSONString();

        JSONObject rec = JSONObject.parseObject(str);
        System.out.println(rec);

        JSONObject da = rec.getJSONObject("data");
        if(da==null){
            System.out.println("no Object");
        }else{
            LabelManagement ma = JSONObject.toJavaObject(da,LabelManagement.class);
            System.out.println(ma.getLabelId());
        }

        JSONArray extList = main.getJSONArray("extList");

        if(extList != null && extList.size()>0){
            for (Object o : extList) {
                JSONObject extobj = (JSONObject) o;
                LabelExt labelExt = new LabelExt();
                labelExt = JSONObject.toJavaObject(extobj, LabelExt.class);
            }
        }else{
            System.out.println("no Array Value");
        }



    }
}
